﻿namespace Chameleon.Storage
{
	using Microsoft.WindowsAzure;
	using Microsoft.WindowsAzure.StorageClient;
	using System.Collections.Generic;
	using System.Linq;

	/// <summary>
	/// Provides a context for storage and retrieval of contiguous data via Azure Storage.
	/// </summary>
	
	public sealed class AzureStorageProvider : IStorageProvider
	{
		#region Fields

			/// <summary>
			/// Account to use for storage operations.
			/// </summary>

			CloudStorageAccount Account;
			

			/// <summary>
			/// Azure storage client.
			/// </summary>

			CloudBlobClient Client;

		#endregion


		#region Methods

			/// <summary>
			/// Returns the collection of containers within the root of the context.
			/// </summary>
			
			public IEnumerable<IStorageContainer> Containers()
			{
				return
					from c in Client.ListContainers()
					select new AzureStorageContainer( c );
			}


			/// <summary>
			/// Returns the specified container from the context.
			/// <para>If the container does not already exist, it will be created.</para>
			/// </summary>
			/// <param name="path">The name of the container or an absolute URI to the container.</param>

			public IStorageContainer Container( string path )
			{
				var container = Client.GetContainerReference( path );
				container.CreateIfNotExist();

				return new AzureStorageContainer( container );
			}

		#endregion


		#region Constructors

			/// <summary>
			/// Initializes a new instance that connects to the specified Azure Storage account.
			/// </summary>
			/// <param name="connection">
			/// Connection string for the Azure Storage account.
			/// <para>For details see: http://msdn.microsoft.com/en-us/library/ee758697.aspx </para>
			/// </param>
			
			public AzureStorageProvider( string connection )
			{
				Account = CloudStorageAccount.Parse( connection );
				Client = Account.CreateCloudBlobClient();
			}

		#endregion
	}
}
